/**
 * Copyright (c) 2007,中企动力华南研发中心<br>
 * All rights reserved.<br>
 */
package com.ce.pms.charge.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.charge.service.IBankCollectionService;
import com.ce.pms.charge.service.IFeeBankService;
import com.ce.pms.charge.service.IPeriodService;
import com.ce.pms.charge.vo.CollectionDetailVO;
import com.ce.pms.charge.vo.CollectionFileVO;
import com.ce.pms.common.util.UpLoadFile;
import com.ce.pms.exception.UILayerException;
import com.sitechasia.webx.components.xtable.util.ExtremeUtils;
import com.sitechasia.webx.core.annotation.Read;
import com.sitechasia.webx.core.support.Page;

/**
 * 功能描述：银行托收action<br>
 * @author 易贤建 创建日期：2008-9-19<br>
 */
public class BankCollectionAction extends PmsBaseAction {

	private IFeeBankService feeBankService = null; //划款银行
	private IPeriodService periodService = null;  //收费周期
	private IBankCollectionService collectionService = null; //银行托收

	private final String FILENAME_KEY = "fileName_key";
	/**
	 * 功能描述:  初始化银行托收主页面<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-19  <br>
	 */
	public String initMain(){
		initCache();
		return "main";
	}
	/**
	 * 功能描述: 初始化银行出盘 <br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-22  <br>
	 */
	public String initOut(){
		initCacheBank();
		return "collectionOut";
	}
	/**
	 * 功能描述:初始化银行回盘<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String initIn(){
		initCacheBank();
		return "collectionIn";
	}
	/**
	 * 功能描述:  <br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-19  <br>
	 */
	public String initOutList(){
		setAttribute("totalRows", Integer.valueOf(0));
		return "outList";
	}

	/**
	 * 功能描述:  初始化出盘文件列表<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-19  <br>
	 */
	public String initInList(){
		setAttribute("totalRows", Integer.valueOf(0));
		return "inList";
	}

	/**
	 * 功能描述:初始化银行出盘明细页面<br>
	 * @param collectionFileId
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String initOutDetail(@Read(key="collectionFileId")Long collectionFileId){
		CollectionFileVO collectionFileVO = collectionService.getCollectionFileById(collectionFileId);
		setAttribute("collectionFileVO", collectionFileVO);
		return "outDetail";
	}
	/**
	 * 功能描述:初始化银行出盘脱手明细列表页面<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String initOutDetailList(){
		setAttribute("totalRows", Integer.valueOf(0));
		return "outDetailList";
	}
	/**
	 * 功能描述:初始化银行回盘详细页面<br>
	 * @param collectionFileId
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String initInDetail(@Read(key="collectionFileId")Long collectionFileId){
		CollectionFileVO collectionFileVO = collectionService.getCollectionFileById(collectionFileId);
		setAttribute("collectionFileVO", collectionFileVO);
		return "inDetail";
	}
	/**
	 * 功能描述:初始化银行托收回盘明细列表<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String initInDetailList(){
		setAttribute("totalRows", Integer.valueOf(0));
		return "inDetailList";
	}

	/**
	 * 功能描述:  根据查询条件查询出盘列表<br>
	 * @param bankId 银行ID
	 * @param periodId  收费周期ID
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-22  <br>
	 */
	public String outList(@Read CollectionFileVO collectionfileVO,
						 @Read(key="ec_p", defaultValue="1") int pageNo,
			             @Read(key="ec_crd",defaultValue="15")int pageSize){
		collectionfileVO.setPageNo(pageNo);
		collectionfileVO.setPageSize(pageSize);

		Page page = collectionService.queryOutBankCollection(collectionfileVO);

		setAttribute("collectionFileList", page.getResult());
		setAttribute("totalRows", Integer.valueOf(String.valueOf(page.getTotalCount())));
		return "outList";
	}
	/**
	 * 功能描述: 根据查询条件查询回盘列表 <br>
	 * @param bankId 银行ID
	 * @param periodId  收费周期ID
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-22  <br>
	 */
	public String inList(@Read CollectionFileVO collectionfileVO,
						 @Read(key="ec_p", defaultValue="1") int pageNo,
			             @Read(key="ec_crd",defaultValue="15")int pageSize){
		collectionfileVO.setPageNo(pageNo);
		collectionfileVO.setPageSize(pageSize);

		Page page = collectionService.queryInBankCollection(collectionfileVO);

		setAttribute("collectionFileList", page.getResult());
		setAttribute("totalRows", Integer.valueOf(String.valueOf(page.getTotalCount())));

		return "inList";
	}
	/**
	 * 功能描述:查询托收明细<br>
	 * @param collectionOutId
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String outDetailList(@Read CollectionDetailVO searchVO){
		searchVO.setPageSize(ExtremeUtils.getPageSize(getRequest()));
		searchVO.setPageNo(ExtremeUtils.getPageNo(getRequest()));

		Page page = collectionService.queryCollectionDetail(searchVO);
		setAttribute("collectionDetailList", page.getResult());
		setAttribute("totalRows", Integer.valueOf(String.valueOf(page.getTotalCount())));
		return "outDetailList";
	}
	/**
	 * 功能描述:查询银行回盘托收明细列表<br>
	 * @param collectionOutId
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String inDetailList(@Read CollectionDetailVO searchVO){
		searchVO.setPageNo(ExtremeUtils.getPageNo(getRequest()));
		searchVO.setPageSize(ExtremeUtils.getPageSize(getRequest()));
		Page page = collectionService.queryCollectionDetail(searchVO);
		setAttribute("collectionDetailList", page.getResult());
		setAttribute("totalRows", Integer.valueOf(String.valueOf(page.getTotalCount())));
		return "inDetailList";
	}

	/**
	 * 功能描述:  银行出盘<br>
	 * Create author:yixianjian <br>
	 * Create on:2008-9-23  <br>
	 * @throws Exception
	 */
	public void outFile(@Read(key="bankId")Long bankId) throws Exception{
		collectionService.out(bankId,getUserId());
	}

	/**
	 * 功能描述:银行回盘<br>
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public String inFile(){
		Map<String,Object> params = getRequestParams();
		HSSFWorkbook inExcel = getInputExcel((FileItem)params.get(FILENAME_KEY));
		String fileName = getFileName((String)params.get("inFileName"));
		collectionService.in(Long.valueOf((String)params.get("bankId")),fileName , inExcel, getUserId());
		return "callBackPage";
	}

	/**
	 * 功能描述:获取出盘文件,并导出 <br>
	 * @param collectionFileId
	 * @throws FileNotFoundException
	 * Create author:yixianjian <br>
	 * Create on:2008-10-14  <br>
	 */
	public void getOutFile(@Read(key="collectionFileId")Long collectionFileId) throws FileNotFoundException{
		CollectionFileVO collectionFileVO = collectionService.getCollectionFileById(collectionFileId);
		String filePath = collectionFileVO.getOutFilePath();
		String fileName = collectionFileVO.getOutFileName();
		writeFile(filePath,fileName);
	}
	/**
	 * 功能描述:获取回盘文件<br>
	 * @param collectionFileId
	 * Create author:yixianjian <br>
	 * Create on:2008-10-14  <br>
	 */
	public void getInFile(@Read(key="collectionFileId")Long collectionFileId){
		CollectionFileVO collectionFileVO = collectionService.getCollectionFileById(collectionFileId);
		String filePath = collectionFileVO.getInFilePath();
		String fileName = collectionFileVO.getInFileName();

		writeFile(filePath,fileName);
	}

	/**
	 * 功能描述:银行回盘前缀验证<br>
	 * @param bankId
	 * @param fileName
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	public void validateInFileName(@Read(key="bankIdForValidate") Long bankId,@Read(key="inFileName")String fileName){
		if(bankId == null){
			renderText(getLocaleMessage("charge:charge_collection_in_bankId_isNull"));
			return;
		}
		if(fileName == null) {
			renderText(getLocaleMessage("charge:charge_collection_in_file_isNull"));
			return;
		}
		String inputFileName = fileName.substring(fileName.lastIndexOf("\\")).substring(1);
		Boolean flag = feeBankService.checkInPreFix(bankId, inputFileName);
		if(flag) renderText("true");
		else renderText(getLocaleMessage("charge:charge_bankCollection_fileName"));
	}

	/**
	 * 功能描述:给定文件路径、文件名,输出到response中<br>
	 * @param filePath
	 * @param fileName
	 * Create author:yixianjian <br>
	 * Create on:2008-10-14  <br>
	 */
	private void writeFile(String filePath,String fileName){
		filePath = filePath.endsWith(File.separator)? filePath : filePath + File.separator ;

		InputStream inputStream;
		try {
			inputStream = new FileInputStream(filePath + fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new UILayerException("charge:bankCollection_bankOutFileNotFount",UILayerException.FAILURE);
		}

		getResponse().setHeader("Content-Disposition", "attachment;filename=" + fileName);
		renderBinary("application/vnd.ms-excel", inputStream);
	}

	/**
	 * 功能描述:读取上传的excel<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-14  <br>
	 */
	private HSSFWorkbook getInputExcel(FileItem fileItem ){
		try {
			return new HSSFWorkbook(fileItem.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
			throw new UILayerException("Failed for getting excel file");
		}
	}
	/**
	 * 功能描述: 从request中获取输入的文件流 <br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-8-27  <br>
	 */
	@SuppressWarnings("unchecked")
	private FileItem getFileItem(){
        DiskFileItemFactory factory=new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        ServletFileUpload fileUpload=new ServletFileUpload(factory);
        FileItem fileItem = null;
        try{
            //开始读取上传信息
            List<FileItem> filedList  = fileUpload.parseRequest(getRequest());
            for(int i = 0; filedList != null && i < filedList.size() ; i++){
            	//如果不是上传的文件  就进入到下一个循环
            	if(filedList.get(i).isFormField()) continue;
            	fileItem = filedList.get(i); break;
            }
        }catch(Exception e){
        	throw new UILayerException("File read failed");
        }
        //如果fileItem 为空 则说明没输入文件  提示用户输入文件
        if(fileItem == null) throw new UILayerException("charge:charge_collection_in_file_not_found");
		return fileItem;
	}

	/**
	 * 功能描述:前台传进来的地址包括路径,这里需要解析下<br>
	 * @param fileName
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-14  <br>
	 */
	private String getFileName(String fileName){
		if(fileName == null) throw new UILayerException("文件名解析失败");

		String pathSeparator = "\\";
		if(!fileName.contains(pathSeparator))  pathSeparator = "/";

		return fileName.substring(fileName.lastIndexOf(pathSeparator) + 1);
	}
	/**
	 * 功能描述: 获取请求的参数<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-10-14  <br>
	 */
	private Map<String,Object> getRequestParams(){
		HashMap<String,Object> params = new HashMap<String, Object>();

        DiskFileItemFactory factory=new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        ServletFileUpload fileUpload=new ServletFileUpload(factory);
        FileItem fileItem = null;
        try{
            //开始读取上传信息
            List<FileItem> filedList  = fileUpload.parseRequest(getRequest());
            for(int i = 0; filedList != null && i < filedList.size() ; i++){
            	fileItem = filedList.get(i);
            	if(fileItem.isFormField())params.put(fileItem.getFieldName(), new String(fileItem.get()));
            	else params.put(FILENAME_KEY, fileItem);
            }
        }catch(Exception e){
        	throw new UILayerException(getLocaleMessage("charge:charege_meterdata_read_file_exception"));
        }
		return params;
	}
	private void initCache(){
		initCacheBank();
		//收费周期
		List periodList = periodService.findPeriodByValidity(null);
		setAttribute("periodList", periodList);
	}

	/**
	 * 功能描述:缓存银行列表<br>
	 * Create author:yixianjian <br>
	 * Create on:2008-10-7  <br>
	 */
	private void initCacheBank(){
		List bankList = feeBankService.getAllBankList();
		setAttribute("bankList", bankList);
	}

	public void setFeeBankService(IFeeBankService feeBankService) {
		this.feeBankService = feeBankService;
	}
	public void setPeriodService(IPeriodService periodService) {
		this.periodService = periodService;
	}
	public void setCollectionService(IBankCollectionService collectionService) {
		this.collectionService = collectionService;
	}
}
